package com.anntly.netty.chatRoom;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {

    private String host;
    private int port;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(boss)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加字符解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            // 添加字符编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            // 自定义处理器
                            pipeline.addLast(new ChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
//            channelFuture.channel().closeFuture().sync();
            Scanner sc = new Scanner(System.in);
            // 获取channel
            Channel channel = channelFuture.channel();
            while (sc.hasNextLine()){
                String msg = sc.nextLine();
                channel.writeAndFlush(msg+"\r\n");
            }
        } finally {
            boss.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ChatClient("127.0.0.1",8888).run();
    }
}
